package com.jg.visitor.config.web;


import com.jg.visitor.common.bean.AppConfigs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@ControllerAdvice
@Configuration
@Slf4j
public class WebConfig implements WebMvcConfigurer {

    @Resource
    private AppConfigs appConfigs;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
                // 拦截所有的请求
                .addMapping("/**")
                // 可跨域的域名，可以为 *
                .allowedOrigins("*")
                .allowCredentials(true)
                // 允许跨域的方法，可以单独配置
                .allowedMethods("*")
                // 允许跨域的请求头，可以单独配置
                .allowedHeaders("*");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //swagger
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        //knife4j
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        //jquery等静态文件访问
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        //图片访问
        String imagesPath = "file:" + appConfigs.getUploadImgPath() + "images/";
        log.info("set imagesPath={}",imagesPath);

        registry.addResourceHandler("/images/**")
                .addResourceLocations(imagesPath);
    }
}
